/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.asu.cse360.service.impl;

import edu.asu.cse360.annotation.TargetEntity;
import edu.asu.cse360.dao.DataAccessObject;
import edu.asu.cse360.model.Chef;
import edu.asu.cse360.model.Employee;
import edu.asu.cse360.model.ItemOrder;
import edu.asu.cse360.model.Restaurant;
import edu.asu.cse360.model.WaitPerson;
import edu.asu.cse360.service.EmployeeService;
import edu.asu.cse360.service.ItemOrderService;
import edu.asu.cse360.service.util.ItemOrderEmployeeAccessor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{

    @Autowired
    @TargetEntity(Employee.class)
    private DataAccessObject<Employee, Integer> employeeDao;

    @Autowired
    private ItemOrderService itemOrderSvc;

    @Override
    public List<Employee> getEmployees(Restaurant restaurant) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("restaurant", restaurant);
        return employeeDao.findList(Employee.FIND_ALL_BY_RESTAURANT, params);
    }

    @Override
    public Employee save(Employee employee) {
        if(employee.getId() == null){
            employeeDao.create(employee);
        }else{
            employeeDao.update(employee);
        }
        return employee;
    }

    @Override
    public void remove(Employee employee) {
        Employee attachedEmployee = employeeDao.read(employee.getId());
        if(attachedEmployee instanceof WaitPerson){
            nullifyOrders((WaitPerson)attachedEmployee);
        }else if(attachedEmployee instanceof Chef){
            nullifyOrders((Chef)attachedEmployee);
        }
        employeeDao.delete(attachedEmployee);
    }

    private void nullifyOrders(WaitPerson waitPerson) {
        List<ItemOrder> itemOrders = itemOrderSvc.findByWaitPerson(waitPerson);
        nullifyOrdersEmployee(itemOrders, ItemOrderEmployeeAccessor.WAIT_PERSON);
    }

    private void nullifyOrders(Chef chef) {
        List<ItemOrder> itemOrders = itemOrderSvc.findByChef(chef);
        nullifyOrdersEmployee(itemOrders, ItemOrderEmployeeAccessor.CHEF);
    }

    private void nullifyOrdersEmployee(List<ItemOrder> itemOrders,ItemOrderEmployeeAccessor accessor) {
        for(ItemOrder itemOrder : itemOrders){
            accessor.setEmployee(itemOrder, null);
            itemOrderSvc.save(itemOrder);
        }
    }

}
